//
//  EditAddressViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/11/2.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "EditAddressViewController.h"

@interface EditAddressViewController ()<UIPickerViewDelegate, UIPickerViewDataSource, UITextViewDelegate>
{
    NSMutableArray *_ProvinceArray;
    NSString *_type;
}
@property (strong, nonatomic) UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UITextField *UserNameTF;
@property (weak, nonatomic) IBOutlet UITextField *PhoneTF;
@property (weak, nonatomic) IBOutlet UITextView *TextView;
@property (weak, nonatomic) IBOutlet UILabel *PrivLabel;
@property (weak, nonatomic) IBOutlet UILabel *CityLabel;
@property (weak, nonatomic) IBOutlet UILabel *AreaLabel;
@property (copy, nonatomic) NSString *SId;
@property (copy, nonatomic) NSString *CityId;
@property (copy, nonatomic) NSString *AreaId;
@property (strong, nonatomic) UIButton *canceBtn;
@property (weak, nonatomic) IBOutlet UILabel *AddressLabel;
@property (strong, nonatomic) UIView *BtnbackView;
@end

@implementation EditAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if ([self.editType isEqualToString:@"edit"]) {
        self.titleLabel.text = @"编辑地址";
        _UserNameTF.text = self.userName;
        _PhoneTF.text = self.userPhone;
    }else{
        self.titleLabel.text = @"添加地址";
    }
    _PhoneTF.keyboardType = UIKeyboardTypeDecimalPad;
    [self createPickerView];
}

//下载省份数据
- (void)downloadProvince
{
    [_ProvinceArray removeAllObjects];
    [self.view loadingOnAnyView];
    [THWManager PostHttp:API(AddressChoose) Parameters:@{@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        [self.view removeAnyView];
        if ([responseObject[@"data"] count] != 0) {
            _ProvinceArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"]];
        }
        [_pickerView reloadAllComponents];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

//下载城市数据
- (void)downloadCity
{
    [_ProvinceArray removeAllObjects];
    [self.view loadingOnAnyView];
    [THWManager PostHttp:API(AddressChoose) Parameters:@{@"userToken":[Utils getUserToken], @"areaId":_SId} Success:^(id responseObject) {
        [self.view removeAnyView];
        if ([responseObject[@"data"] count] != 0) {
            _ProvinceArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"]];
        }
        [_pickerView reloadAllComponents];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

//下载地区数据
- (void)downloadArea
{
    [_ProvinceArray removeAllObjects];
    [self.view loadingOnAnyView];
    [THWManager PostHttp:API(AddressChoose) Parameters:@{@"userToken":[Utils getUserToken], @"areaId":_CityId} Success:^(id responseObject) {
        [self.view removeAnyView];
        if ([responseObject[@"data"] count] != 0) {
            _ProvinceArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"]];
        }
        [_pickerView reloadAllComponents];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

- (void)createPickerView
{
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT-200, WIDTH, 200)];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.backgroundColor = [UIColor colorWithHex:0x999999];
    [_pickerView selectRow:0 inComponent:0 animated:YES];
    _pickerView.hidden = YES;
    [self.view addSubview:_pickerView];
    
    _BtnbackView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT-230, WIDTH, 30)];
    _BtnbackView.backgroundColor = [UIColor colorWithHex:0x999999];
    _BtnbackView.hidden = YES;
    [self.view addSubview:_BtnbackView];
    
    _canceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _canceBtn.frame = CGRectMake(10, 10, 50, 30);
    [_canceBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_canceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_canceBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [_BtnbackView addSubview:_canceBtn];
}

- (void)btnClick
{
    _BtnbackView.hidden = YES;
    _pickerView.hidden = YES;
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _ProvinceArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *str = _ProvinceArray[row][@"areaName"];
    return str;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([_type isEqualToString:@"s"]) {
        _PrivLabel.text = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaName"]];
        _SId = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaId"]];
        _CityLabel.text = @"";
    }else if ([_type isEqualToString:@"city"]) {
        _CityLabel.text = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaName"]];
        _CityId = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaId"]];
        _AreaLabel.text = @"";
    }else{
        _AreaLabel.text = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaName"]];
        _AreaId = [NSString stringWithFormat:@"%@", _ProvinceArray[row][@"areaId"]];
    }
    
}

- (IBAction)PrviClick:(UIButton *)sender {
    [_UserNameTF resignFirstResponder];
    [_PhoneTF resignFirstResponder];
    [_TextView resignFirstResponder];
    _type = @"s";
    [self downloadProvince];
    _BtnbackView.hidden = NO;
    _pickerView.hidden = NO;
    
}
- (IBAction)CityClick:(UIButton *)sender {
    if (![TXUtilsString isBlankString:_SId]) {
        [_UserNameTF resignFirstResponder];
        [_PhoneTF resignFirstResponder];
        [_TextView resignFirstResponder];
        _type = @"city";
        [self downloadCity];
        _BtnbackView.hidden = NO;
        _pickerView.hidden = NO;
    }else{
        [self.view Message:@"请输入省份"];
    }
    
}
- (IBAction)AreaClick:(UIButton *)sender {
    if (![TXUtilsString isBlankString:_CityId]) {
        [_UserNameTF resignFirstResponder];
        [_PhoneTF resignFirstResponder];
        [_TextView resignFirstResponder];
        _type = @"area";
        [self downloadArea];
        _BtnbackView.hidden = NO;
        _pickerView.hidden = NO;
    }else{
        [self.view Message:@"请输入城市"];
    }
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _AddressLabel.hidden = YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (_TextView.text.length != 0) {
        _AddressLabel.hidden = YES;
    }else{
        _AddressLabel.hidden = NO;
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_UserNameTF resignFirstResponder];
    [_PhoneTF resignFirstResponder];
    [_TextView resignFirstResponder];
}

- (IBAction)AddClick:(UIButton *)sender
{
    if ([self.editType isEqualToString:@"edit"]) {
        if (_SId.length != 0 && _CityId.length != 0 && _AreaId.length != 0) {
            [self.view loadingOnAnyView];
            [THWManager PostHttp:API(MineEditAddressClick) Parameters:@{@"userToken":[Utils getUserToken], @"userName":_UserNameTF.text, @"userPhone":_PhoneTF.text, @"areaIdPath":[NSString stringWithFormat:@"%@_%@_%@_", _SId, _CityId, _AreaId], @"areaId":_AreaId, @"isDefault":@"1", @"userAddress":_TextView.text, @"addressId":self.AddressId} Success:^(id responseObject) {
                [self.view removeAnyView];
                if ([String(responseObject[@"status_code"]) isEqualToString:@"1000"]) {
                    [self.view Message:responseObject[@"msg"]];
                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"MineAddressRefresh" object:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }else{
                    [self.view Message:responseObject[@"msg"]];
                }
            } andFalse:^(NSError *error) {
                [self.view removeAnyView];
            }];
        }else{
            [self.view Message:@"请输入完整信息"];
        }
        
    }else{
        if (_SId.length != 0 && _CityId.length != 0 && _AreaId.length != 0 && _UserNameTF.text.length != 0 && _PhoneTF.text.length != 0) {
            [self.view loadingOnAnyView];
            [THWManager PostHttp:API(MineAddAddress) Parameters:@{@"userToken":[Utils getUserToken], @"userName":_UserNameTF.text, @"userPhone":_PhoneTF.text, @"areaIdPath":[NSString stringWithFormat:@"%@_%@_%@_", _SId, _CityId, _AreaId], @"areaId":_AreaId, @"isDefault":@"1", @"userAddress":_TextView.text} Success:^(id responseObject) {
                [self.view removeAnyView];
                if ([String(responseObject[@"status_code"]) isEqualToString:@"1000"]) {
                    [self.view Message:responseObject[@"msg"]];
                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"MineAddressRefresh" object:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }else{
                    [self.view Message:responseObject[@"msg"]];
                }
            } andFalse:^(NSError *error) {
                [self.view removeAnyView];
            }];
        }else{
            [self.view Message:@"请输入完整信息"];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
